// i.d(t, { Z: () => SweepTextureLoader })
import * as THREE from "three"
import Logger from "../utils/Logger"
import funcUtil from "../utils/func.util"
import resolutionEnum from "../enum/resolution.enum"
import ModelDataModule from "../module/ModelDataModule"
import Sweep from "../object/Sweep"
const a = new Logger("api"),
  l = {
    [resolutionEnum.BASE]: 256,
    [resolutionEnum.STANDARD]: 1024,
    [resolutionEnum.HIGH]: 2048,
    [resolutionEnum.ULTRAHIGH]: 4096
  }
export default class SweepTextureLoader {
  urls: ModelDataModule["signedUrls"]
  sweepCubeTextures: Record<string, THREE.CubeTexture>
  constructor(e) {
    this.urls = e
    this.sweepCubeTextures = {}
  }
  useTexture(e) {
    const t = this.getTexture(e)
    if (!t) throw Error(`Texture for sweep ${e} not loaded before using`)
    return t
  }
  loadFace(e, t, i, s) {
    return this.loadFaceImage(e, t, i, s).then(e => {
      const t = new THREE.Texture(e as any)
      return (t.needsUpdate = !0), t
    })
  }
  load(e: Sweep, t = resolutionEnum.STANDARD): Promise<THREE.CubeTexture> {
    const i = this.sweepCubeTextures[e.id]
    if (i) {
      a.debug("Skipping load of pano, already loaded")
      return new Promise((e, t) => {
        e(i)
      })
    }
    const s = [2, 4, 0, 5, 1, 3].map(i => this.loadFaceImage(e, t, i))
    const o = Promise.all(s).then(t => {
      const i = new THREE.CubeTexture(t)
      i.flipY = !1
      i.needsUpdate = !0
      this.sweepCubeTextures[e.id] = i
      return i
    })
    o.catch(() => {
      a.error(`Downloading cubemap for pano ${e.id} failed`)
    })
    return o
  }
  unload(e) {
    const t = this.sweepCubeTextures[e]
    if (!t) throw Error(`Texture for sweep ${e} not loaded before unloading`)
    t.dispose(), (this.sweepCubeTextures[e] = null)
  }
  unloadAll(e) {
    const t = funcUtil.valToFalse(e)
    for (const e of Object.keys(this.sweepCubeTextures)) this.sweepCubeTextures[e] && !t[e] && this.unload(e)
  }
  async loadFaceImage(e: Sweep, t: string, i: number, n?) {
    const s = l[t]
    const r = await e.getFaceUrl(t, i)
    return this.urls.getImageBitmap(r, s, s, n)
  }
  getTexture(e) {
    return this.sweepCubeTextures[e]
  }
}
